import React, { useState } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';

const CustomPage = () => {
    const navigate = useNavigate();
    const location = useLocation();
    const { data, selectedTableName } = location.state || {};
    const [rows, setRows] = useState(data);
    const [topRowsCount, setTopRowsCount] = useState('');
    const [isRelated, setIsRelated] = useState(false);
    const [isReverse, setIsReverse] = useState(false);
    const [showDropdown, setShowDropdown] = useState(false);
    const [selectedColumnName, setSelectedColumnName] = useState('');

    const handleCommentChange = (index, newComment) => {
        const updatedRows = [...rows];
        updatedRows[index].comments = newComment;
        setRows(updatedRows);
    };

    const handleCheckboxChange = (index) => {
        const updatedRows = [...rows];
        updatedRows[index].isChecked = !updatedRows[index].isChecked;
        setRows(updatedRows);
    };

    const handleNext = async () => {
        let selectedRows;
        // 检查是否有行被选中
        const hasCheckedRows = rows.some(row => row.isChecked);
        if (hasCheckedRows) {
            // 如果有选中的行，过滤出选中的行
            selectedRows = rows.filter(row => row.isChecked);
        } else {
            // 如果没有选中的行，默认选中全部
            selectedRows = rows;
        }

        const rowsDatas = selectedRows.map(row => ({
            columnName: row.columnName,
            comments: row.comments
        }));

        try {
            const params = new URLSearchParams({
                tableName: selectedTableName,
                rows: topRowsCount,
                isSort: isReverse,
                sortColumn: selectedColumnName
            });
            console.log("Request params:", params.toString());

            const response = await fetch(`http://127.0.0.1:9991/api/admin/demo/conditionSelect?${params.toString()}`);

            if (!response.ok) {
                throw new Error('Network response was not ok');
            }

            const result = await response.json();
            console.log('API response:', result.data);
            const queryData = result.data;

            if (isRelated) {
                navigate('/mergeData', {
                    state: {
                        rowsDatas,
                        selectedTableName
                    }
                });
            } else {
                navigate('/button', {
                    state: {
                        rowsDatas,
                        queryData
                    }
                });
            }
        } catch (error) {
            console.error('Error calling API:', error);
        }
    };

    const handleReverseChange = (e) => {
        const checked = e.target.checked;
        setIsReverse(checked);
        setShowDropdown(checked);
        console.log('Show dropdown:', showDropdown); // 调试信息
    };

    const handleSelectChange = (e) => {
        const value = e.target.value;
        setSelectedColumnName(value);
        console.log('Selected column name:', value);
    };

    return (
        <div style={{
            display: 'flex',
            flexDirection: 'column',
            alignItems: 'center',
            paddingTop: '50px',
            minHeight: '100vh'
        }}>
            <h1>自定义字段名称</h1>
            <table border="1">
                <thead>
                    <tr>
                        <th>复选</th>
                        <th>字段名称</th>
                        <th>Excel列名</th>
                    </tr>
                </thead>
                <tbody>
                    {rows.map((row, index) => (
                        <tr key={index}>
                            <td>
                                <input
                                    type="checkbox"
                                    checked={row.isChecked || false}
                                    onChange={() => handleCheckboxChange(index)}
                                />
                            </td>
                            <td>{row.columnName}</td>
                            <td>
                                <input
                                    type="text"
                                    value={row.comments}
                                    onChange={(e) => handleCommentChange(index, e.target.value)}
                                />
                            </td>
                        </tr>
                    ))}
                </tbody>
            </table>
            <div style={{ display: 'flex', alignItems: 'center', marginTop: 20 }}>
                <label htmlFor="topRowsCount">前几条: </label>
                <input
                    type="number"
                    id="topRowsCount"
                    value={topRowsCount}
                    onChange={(e) => setTopRowsCount(e.target.value)}
                    style={{ marginLeft: 10 }}
                />
            </div>
            <div style={{
                display: 'flex',
                justifyContent: 'center',
                width: '100%',
                maxWidth: '800px',
                marginTop: 10
            }}>
                <div style={{ display: 'flex', alignItems: 'center', marginRight: 150 }}>
                    <input
                        type="checkbox"
                        id="isRelated"
                        checked={isRelated}
                        onChange={(e) => setIsRelated(e.target.checked)}
                    />
                    <label htmlFor="isRelated" style={{ marginLeft: 1 }}>额外关联信息</label>
                </div>
                <div style={{ display: 'flex', alignItems: 'center' }}>
                    <input
                        type="checkbox"
                        id="isReverse"
                        checked={isReverse}
                        onChange={handleReverseChange}
                    />
                    <label htmlFor="isReverse" style={{ marginLeft: 2 }}>是否倒序</label>
                    {showDropdown && (
                        <select style={{ marginLeft: 10 }} onChange={handleSelectChange}>
                            <option value="">请选择</option>
                            {rows.map((row, index) => (
                                <option key={index} value={row.columnName}>
                                    {row.columnName}
                                </option>
                            ))}
                        </select>
                    )}
                </div>
            </div>
            <div style={{ width: '100%', maxWidth: '800px', display: 'flex', justifyContent: 'flex-end', marginTop: '20px' }}>
                <button onClick={handleNext}>下一步</button>
            </div>
        </div>
    );
};

export default CustomPage;